<template>
  <div class="container">
    <div class="tabber">
      <a-space size="medium" direction="vertical" fill>
        <a-space>
          <a-input placeholder="请输入标题搜索" v-model="search"></a-input>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
        </a-space>
        <a-space>
          <a-button
            type="primary"
            @click="
              visible = true;
              isAdd = true;
              form = {};
              form.type = 1;
              form.status = 1;
            "
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增</template>
          </a-button>
          <a-button type="primary" @click="handleRefresh">
            <template #icon>
              <icon-loop />
            </template>
            <template #default>刷新</template>
          </a-button>
          <a-button
            status="danger"
            @click="deleteAll = selectedKeys.length > 0 ? true : false"
          >
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-space>
      </a-space>
    </div>
    <a-table
      row-key="id"
      :columns="columns"
      :data="data"
      column-resizable
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      :bordered="{ cell: true }"
      :scroll="{ x: 'min-content' }"
      size="small"
      :table-layout-fixed="true"
    >
      <template #cover="{ record }">
        <a-image
          fit="cover"
          width="64"
          height="64"
          :src="BASE_URL + record.cover"
        />
      </template>
      <template #organizer="{ record }">
        <a-popover title="用户">
          <a-avatar :imageUrl="BASE_URL + record.organizer.avatar"> </a-avatar>
          <template #content>
            <p>id：{{ record.organizer.id }}</p>
            <p>昵称：{{ record.organizer.nikeName }}</p>
          </template>
        </a-popover>
      </template>
      <template #expense="{ record }">
        <a-tag color="orangered">{{
          record.cost > 0 ? record.code + "元" : "免费"
        }}</a-tag>
      </template>
      <template #status="{ record }">
        <a-tag v-if="record.status === 1" color="blue"> 报名中 </a-tag>
        <a-tag v-if="record.status === 2" color="pinkpurple"> 活动中 </a-tag>
        <a-tag v-if="record.status === 3" color="gray"> 已结束 </a-tag>
        <a-tag v-if="record.status === 4" color="gray"> 已取消</a-tag>
      </template>
      <template #number="{ record }">
        <a-space>
          <div>
            {{ record.currentParticipants }} / {{ record.maxParticipants }} 人
          </div>
          <a-button
            size="mini"
            @click="
              getUserListData(record.id);
              showApplyUser = true;
            "
            >查看</a-button
          >
        </a-space>
      </template>
      <template #applyTime="{ record }">
        {{ formatTime(record.startTime) }} - {{ formatTime(record.endTime) }}
      </template>
      <template #eventTime="{ record }">
        {{ formatTime(record.eventTime) }}
      </template>
      <template #optional="{ record }">
        <a-button
          size="mini"
          type="primary"
          style="margin-right: 5px"
          @click="editorHanddle(record)"
          >编辑</a-button
        >
        <a-button size="mini" status="danger" @click="deleteHanddle(record)"
          >删除</a-button
        >
      </template>
    </a-table>
  </div>
  <!-- 编辑弹框 -->
  <a-modal
    v-model:visible="visible"
    :title="isAdd ? '添加数据' : '修改数据'"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <!-- <a-typography-text type="secondary" style="margin-left: 10vh;margin-bottom: 10px;">id:{{ form.id
          }}</a-typography-text> -->
    <a-form :model="form" style="padding-right: 40px">
      <a-form-item label="ID" v-if="!isAdd">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item label="封面">
        <a-upload
          v-if="visible"
          list-type="picture-card"
          :action="BASE_URL + '/api/upload'"
          :default-file-list="
            isAdd
              ? []
              : [
                  {
                    uid: '2392320832',
                    name: '20200717-103937.png',
                    url: BASE_URL + form.cover,
                  },
                ]
          "
          @success="onUploadSuccess"
          name="files"
          image-preview
          :limit="1"
        />
      </a-form-item>
      <a-form-item label="报名人数">
        <a-input v-model="form.maxParticipants" />
      </a-form-item>
      <a-form-item label="标题">
        <a-input v-model="form.title" />
      </a-form-item>
      <a-form-item label="地点">
        <a-input v-model="form.location" />
      </a-form-item>
      <a-form-item label="活动时间">
        <a-date-picker
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          v-model="form.eventTime"
        />
      </a-form-item>

      <a-form-item label="状态">
        <a-select v-model="form.status">
          <a-option :value="1">报名中</a-option>
          <a-option :value="2">活动中</a-option>
          <a-option :value="3">已结束</a-option>
          <a-option :value="4">已取消</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea
          :auto-size="{ minRows: 4, maxRows: 8 }"
          placeholder="请输入描述内容"
          v-model="form.description"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除弹框 -->
  <a-modal v-model:visible="delvalue" title="确认删除" @before-ok="delBeforeOk">
    <a-form :model="form">
      <a-form-item field="id" label="ID">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item field="name" label="标题">
        <a-input disabled v-model="form.title" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除已选的 -->
  <a-modal v-model:visible="deleteAll" @before-ok="handleDeleteAll">
    <template #title> 警告 </template>
    <div>是否删除已选 {{ selectedKeys.length }} 项数据？</div>
  </a-modal>
  <!-- 查看报名人数 -->
  <a-modal
    title="活动报名用户"
    v-model:visible="showApplyUser"
    @before-ok="handleApplyUserAll"
  >
    <a-scrollbar type="track" style="height: 400px; overflow: auto">
      <a-list>
        <a-list-item v-for="item in userList" :key="item.id">
          <a-list-item-meta
            :title="item.participant.nikeName"
            :description="`id：${item.participant.id} - 邮箱：${item.participant.email}`"
          >
            <template #avatar>
              <a-avatar shape="square">
                <img alt="avatar" :src="BASE_URL + item.participant.avatar" />
              </a-avatar>
            </template>
          </a-list-item-meta>
        </a-list-item>
      </a-list>
    </a-scrollbar>
  </a-modal>
</template>

<script setup>
import { BASE_URL } from "../../constant/index";
import { reactive, ref, onMounted, computed } from "vue";
import { formatTime } from "../../utils/dataUtils";
import {
  getActivityListApi,
  deleteActivityApi,
  updateActivityApi,
  postActivityApi,
  getActivityApplyUserListApi,
  deleteActivityApplyUserApi,
} from "../../api/activity.js";
import {
  getRidingListApi,
  getRidingApplyUserListApi,
  putRidingApi,
  postRiddingApi,
  deleteRidingApi
} from "../../api/riding.js";
import {
  IconPlus,
  IconSearch,
  IconLoop,
  IconDelete,
} from "@arco-design/web-vue/es/icon";

import { Message, Modal } from "@arco-design/web-vue";

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});
const pagination = { pageSize: 10 };
const columns = [
  {
    title: "id",
    dataIndex: "id",
    fixed: "left",
    width: 150,
    ellipsis: true,
    tooltip: true,
    align: "center",
  },

  {
    title: "发布者",
    slotName: "organizer",
    width: 80,
    align: "center",
  },
  {
    title: "封面",
    slotName: "cover",
    width: 100,
    align: "center",
  },
  {
    title: "标题",
    dataIndex: "title",

    ellipsis: true,
    tooltip: true,
    width: 200,
    align: "center",
  },

  {
    title: "状态",
    slotName: "status",
    width: 100,
    align: "center",
  },

  {
    title: "报名人数",
    slotName: "number",
    width: 150,
    align: "center",
  },
  {
    title: "活动时间",
    slotName: "eventTime",
    width: 200,
    align: "center",
  },
  {
    title: "地址",
    dataIndex: "location",
    ellipsis: true,
    tooltip: true,
    width: 250,
  },
  {
    title: "描述",
    dataIndex: "description",
    ellipsis: true,
    tooltip: true,
    width: 250,
  },
  {
    title: "创建时间",
    dataIndex: "createdAt",
    width: 220,
    align: "center",
  },
  {
    title: "操作",
    fixed: "right",
    width: 200,
    slotName: "optional",
    align: "center",
  },
];

const data = ref([]);
const limit = ref(1000);
const page = ref(1);
// 获取列表数据
async function getListData() {
  const getRes = await getRidingListApi({
    limit: limit.value,
    page: page.value,
  });
  console.log(getRes);
  console.log(getRes);
  if (getRes.code === 200) {
    const list = getRes.data.list.map((item) => {
      return {
        ...item,
        section: [item.startTime, item.endTime],
      };
    });
    data.value = list;
  }
}

// 获取用户数据
onMounted(() => {
  getListData();
});

// 点击刷新按钮
function handleRefresh() {
  data.value = [];
  getListData();
}
const deleteAll = ref(false);
// 已选择的数据
const selectedKeys = ref([]);
// 点击删除按钮
async function handleDeleteAll(done) {
  console.log(selectedKeys.value);
  const pra = selectedKeys.value.map((id) => {
    return new Promise(async (resolve, reject) => {
      const delRes = await deleteRidingApi({ id });
      console.log(delRes);
      if (delRes.code === 200) {
        resolve(delRes);
      } else {
        reject(delRes);
      }
    });
  });
  try {
    await Promise.all(pra);
    Message.success("批量删除成功");
    done();
    getListData();
  } catch (err) {
    Message.error("批量删除失败");
  }
  console.log("结束");

  return false;
}

const searchType = ref("全部");
const search = ref("");
async function handleSearch() {
  await getListData();
  data.value = data.value.filter((item) => {
    return item.title.includes(search.value);
  });
}
// 上传图片回调
function onUploadSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const cover = res.response.data[0];
    form.value.cover = cover;
    console.log(cover);
  }
}

// 显示编辑弹框
const visible = ref(false);
const form = ref({});
const isAdd = ref(false);
// 取消弹框
function handleCancel() {
  isAdd.value = false;
  form.value = {};
}
// 点击编辑按钮
function editorHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  //   form.value = item;
  visible.value = true;
}
// 确认修改按钮
async function handleBeforeOk(done) {
  if (isAdd.value) {
    await handleAdd(done);
  } else {
    await handleUpdate(done);
  }
  // form.value = {};
  return false;
}
// 新增逻辑
async function handleAdd(done) {
  console.log(form.value);
  console.log(form.value);
  const {
    cover,
    description,
    id,
    title,
    maxParticipants,
    eventTime,
    location,
    currentParticipants,
  } = form.value;

  console.log(1);
  if (!cover) {
    Message.error("封面不能为空");
    return false;
  }
  if (!title) {
    Message.error("标题不能为空");
    return false;
  }
  if (!location) {
    Message.error("请输入地址");
    return false;
  }
  if (!description) {
    Message.error("描述不能为空");
    return false;
  }
  if (!eventTime) {
    Message.error("活动时间不能为空");
    return false;
  }
  if (isNaN(Number(maxParticipants))) {
    Message.error("报名人数人数必须为数字");
    return false;
  }
  if (Number(maxParticipants) <= 0) {
    Message.error("报名人数必须大于0");
    return false;
  }
  if (currentParticipants > maxParticipants) {
    Message.error("报名人数不能大于最大人数");
    return false;
  }

  const postRes = await postRiddingApi({
    id,
    cover,
    title,
    location,
    description,
    maxParticipants: Number(maxParticipants),
    eventTime,
  });

  console.log(postRes);
  if (postRes.code === 200) {
    Message.success("新增成功");
    await getListData();
    done();
  } else {
    console.log(postRes);
    Message.error(postRes.message);
    return false;
  }
}
// 更新逻辑
async function handleUpdate(done) {
  console.log(form.value);
  const {
    cover,
    description,
    id,
    status,
    title,
    maxParticipants,
    eventTime,
    location,
    currentParticipants,
  } = form.value;

  console.log(1);
  if (!cover) {
    Message.error("封面不能为空");
    return false;
  }
  if (!title) {
    Message.error("标题不能为空");
    return false;
  }
  if (!location) {
    Message.error("请输入地址");
    return false;
  }
  if (!description) {
    Message.error("描述不能为空");
    return false;
  }
  if (!eventTime) {
    Message.error("活动时间不能为空");
    return false;
  }
  if (isNaN(Number(maxParticipants))) {
    Message.error("报名人数人数必须为数字");
    return false;
  }
  if (currentParticipants > maxParticipants) {
    Message.error("报名人数不能大于最大人数");
    return false;
  }
  const putRes = await putRidingApi({
    id,
    cover,
    title,
    location,
    description,
    maxParticipants,
    eventTime,
    status,
  });
  console.log(putRes);
  if (putRes.code === 200) {
    Message.success("更新成功");
    await getListData();
    done();
  } else {
    Message.error(putRes.message);
    return false;
  }
  return false;
}

// 删除弹框
const delvalue = ref(false);
// 点击删除按钮
function deleteHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  delvalue.value = true;
}
// 确认删除
async function delBeforeOk() {
  const { id } = form.value;
  console.log(id);
  const delRes = await deleteRidingApi({ id });
  console.log(delRes);
  if (delRes.code === 200) {
    Message.info("删除成功");
    // 更新数据
    getListData();
    delvalue.value = false;
  } else {
    Message.error("删除失败");
    return false;
  }
}

// 查看报名人数
const userList = ref([]);
const showApplyUser = ref(false);
async function getUserListData(id) {
  console.log(id);
  const resRes = await getRidingApplyUserListApi({
    id,
  });
  if (resRes.code == 200) {
    userList.value = resRes.data;
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 14px;
  box-sizing: border-box;
  .tabber {
    padding-bottom: 14px;
  }
}
</style>
